<template>
  <div class="sequence-management">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 序列号配置管理 -->
      <el-tab-pane label="序列号配置管理" name="config">
        <div class="config-section">
          <!-- 搜索栏 -->
          <el-form :inline="true" :model="queryForm" class="search-form">
            <el-form-item label="配置名称">
              <el-input v-model="queryForm.name" placeholder="请输入配置名称" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="配置编码">
              <el-input v-model="queryForm.code" placeholder="请输入配置编码" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loadConfigs">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetQuery">重置</el-button>
              <el-button type="primary" @click="showConfigDialog()">
                <el-icon><Plus /></el-icon>
                新增配置
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 配置列表表格 -->
          <el-card class="table-card" shadow="never">
            <el-table :data="configList" border v-loading="loading" style="width: 100%;" stripe>
              <el-table-column prop="name" label="配置名称" min-width="120" show-overflow-tooltip />
              <el-table-column prop="code" label="配置编码" min-width="120" show-overflow-tooltip />
              <el-table-column label="前缀配置" min-width="180">
                <template #default="{ row }">
                  <div style="display: flex; align-items: center;">
                    <el-tag v-if="row.prefixType === 'TIME'" type="warning" size="small" style="margin-right: 8px;">
                      时间格式
                    </el-tag>
                    <el-tag v-else type="info" size="small" style="margin-right: 8px;">
                      文本
                    </el-tag>
                    <span style="color: #606266;">{{ row.prefixType === 'TIME' ? row.timePrefix : row.prefix || '-' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="长度配置" min-width="140">
                <template #default="{ row }">
                  <div style="display: flex; align-items: center;">
                    <el-tag v-if="row.completion === 'true'" type="success" size="small" effect="plain" style="margin-right: 8px;">
                      补0
                    </el-tag>
                    <span style="font-weight: 500; color: #409eff;">{{ row.length }} 位</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="取值范围" min-width="160">
                <template #default="{ row }">
                  <div v-if="row.valueRange === 'true'" style="display: flex; align-items: center;">
                    <el-icon style="color: #67c23a; margin-right: 4px;"><Check /></el-icon>
                    <span style="color: #606266;">{{ row.minValue }} ~ {{ row.maxValue }}</span>
                  </div>
                  <div v-else style="display: flex; align-items: center;">
                    <el-icon style="color: #909399; margin-right: 4px;"><Close /></el-icon>
                    <span style="color: #909399;">不限制</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="step" label="步长" width="80" align="center">
                <template #default="{ row }">
                  <el-tag type="primary" size="small" effect="plain">+{{ row.step }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="循环" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.cycle === '1' ? 'success' : 'info'" size="small">
                    {{ row.cycle === '1' ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="后缀" min-width="100">
                <template #default="{ row }">
                  <span v-if="row.suffixConf === 'true'" style="color: #606266;">{{ row.suffix || '-' }}</span>
                  <span v-else style="color: #909399;">-</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" fixed="right" align="center">
                <template #default="{ row }">
                  <el-button size="small" type="primary" link @click="showConfigDialog(row)">
                    <el-icon style="margin-right: 4px;"><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" link @click="deleteConfig(row.id)">
                    <el-icon style="margin-right: 4px;"><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="pagination.page"
                v-model:page-size="pagination.size"
                :total="pagination.total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="loadConfigs"
                @current-change="loadConfigs"
                background
              />
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- 序列号生成测试 -->
      <el-tab-pane label="序列号生成测试" name="generate">
        <div class="generate-section">
          <el-card>
            <template #header>
              <span>序列号生成</span>
            </template>
            <el-form :model="generateForm" label-width="120px">
              <el-form-item label="选择配置">
                <el-select v-model="generateForm.code" placeholder="请选择配置编码" style="width: 300px;">
                  <el-option
                    v-for="config in configList"
                    :key="config.code"
                    :label="`${config.name} (${config.code})`"
                    :value="config.code"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="generateSequence" :loading="generating">
                  生成序列号
                </el-button>
                <el-button @click="clearHistory">清空历史</el-button>
              </el-form-item>
            </el-form>

            <!-- 生成历史 -->
            <el-divider>生成历史</el-divider>
            <el-table :data="generatedList" border max-height="400">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="code" label="配置编码" width="150" />
              <el-table-column prop="sequence" label="生成序列号" />
              <el-table-column prop="time" label="生成时间" width="180" />
            </el-table>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 配置编辑对话框 -->
    <el-dialog
      v-model="configDialogVisible"
      :title="configDialogTitle"
      width="700px"
      @close="resetConfigForm"
    >
      <el-form ref="configFormRef" :model="configForm" :rules="configRules" label-width="130px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配置名称" prop="name">
              <el-input v-model="configForm.name" placeholder="请输入配置名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配置编码" prop="code">
              <el-input v-model="configForm.code" placeholder="请输入配置编码" :disabled="isEdit" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="长度补全">
              <el-switch v-model="configForm.completion" active-value="true" inactive-value="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="序列号长度" prop="length">
              <el-input-number v-model="configForm.length" :min="1" :max="20" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="前缀类型">
              <el-radio-group v-model="configForm.prefixType">
                <el-radio label="TEXT">文本</el-radio>
                <el-radio label="TIME">时间格式</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="configForm.prefixType === 'TEXT'" label="文本前缀">
              <el-input v-model="configForm.prefix" placeholder="如：ABC" />
            </el-form-item>
            <el-form-item v-else label="时间格式">
              <el-input v-model="configForm.timePrefix" placeholder="如：yyyyMMdd" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="启用后缀">
              <el-switch v-model="configForm.suffixConf" active-value="true" inactive-value="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="configForm.suffixConf === 'true'" label="后缀">
              <el-input v-model="configForm.suffix" placeholder="请输入后缀" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="启用取值范围">
              <el-switch v-model="configForm.valueRange" active-value="true" inactive-value="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="步长" prop="step">
              <el-input-number v-model="configForm.step" :min="1" :max="1000" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="configForm.valueRange === 'true'" :gutter="20">
          <el-col :span="12">
            <el-form-item label="最小值" prop="minValue">
              <el-input-number v-model="configForm.minValue" :min="0" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大值" prop="maxValue">
              <el-input-number v-model="configForm.maxValue" :min="0" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="是否循环">
          <el-switch v-model="configForm.cycle" active-value="1" inactive-value="0" />
          <span style="margin-left: 10px; color: #999;">序列号超过最大值时是否从最小值重新开始</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="configDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitConfig" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Check, Close } from '@element-plus/icons-vue'
import { 
  getSequenceConfigList,
  createSequenceConfig,
  updateSequenceConfig,
  deleteSequenceConfig,
  generateSequence
} from '../utils/api'

export default {
  name: 'SequenceManagement',
  components: {
    Search,
    Plus,
    Edit,
    Delete,
    Check,
    Close
  },
  setup() {
    const activeTab = ref('config')
    const loading = ref(false)
    const generating = ref(false)
    const submitting = ref(false)
    const configDialogVisible = ref(false)
    const isEdit = ref(false)
    const configFormRef = ref()

    // 查询表单
    const queryForm = reactive({
      name: '',
      code: ''
    })

    // 分页
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 配置列表
    const configList = ref([])

    // 配置表单
    const configForm = reactive({
      id: '',
      name: '',
      code: '',
      completion: 'true',
      length: 4,
      valueRange: 'false',
      prefixType: 'TEXT',
      timePrefix: 'yyyyMMdd',
      prefix: '',
      suffixConf: 'false',
      suffix: '',
      minValue: 0,
      maxValue: 999999,
      step: 1,
      cycle: '0'
    })

    // 表单验证规则
    const configRules = {
      name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
      code: [{ required: true, message: '请输入配置编码', trigger: 'blur' }],
      length: [{ required: true, message: '请输入序列号长度', trigger: 'blur' }],
      step: [{ required: true, message: '请输入步长', trigger: 'blur' }]
    }

    // 生成表单
    const generateForm = reactive({
      code: ''
    })

    // 生成历史
    const generatedList = ref([])

    // 加载配置列表
    const loadConfigs = async () => {
      loading.value = true
      try {
        const response = await getSequenceConfigList({
          page: pagination.page,
          size: pagination.size,
          name: queryForm.name,
          code: queryForm.code
        })
        
        if (response.data.code === 200) {
          const data = response.data.data
          configList.value = data.list || []
          pagination.total = data.total || 0
        } else {
          ElMessage.error(response.data.message || '加载配置失败')
        }
      } catch (error) {
        console.error('加载配置失败：', error)
        ElMessage.error('加载配置失败')
      } finally {
        loading.value = false
      }
    }

    // 重置查询
    const resetQuery = () => {
      queryForm.name = ''
      queryForm.code = ''
      pagination.page = 1
      loadConfigs()
    }

    // 显示配置对话框
    const showConfigDialog = (row) => {
      if (row) {
        // 编辑
        isEdit.value = true
        Object.assign(configForm, row)
      } else {
        // 新增
        isEdit.value = false
        resetConfigForm()
      }
      configDialogVisible.value = true
    }

    // 重置配置表单
    const resetConfigForm = () => {
      if (configFormRef.value) {
        configFormRef.value.resetFields()
      }
      Object.assign(configForm, {
        id: '',
        name: '',
        code: '',
        completion: 'true',
        length: 4,
        valueRange: 'false',
        prefixType: 'TEXT',
        timePrefix: 'yyyyMMdd',
        prefix: '',
        suffixConf: 'false',
        suffix: '',
        minValue: 0,
        maxValue: 999999,
        step: 1,
        cycle: '0'
      })
    }

    // 提交配置
    const submitConfig = async () => {
      if (!configFormRef.value) return
      
      await configFormRef.value.validate(async (valid) => {
        if (!valid) return
        
        submitting.value = true
        try {
          let response
          if (isEdit.value) {
            // 更新
            response = await updateSequenceConfig(configForm.id, configForm)
          } else {
            // 创建
            response = await createSequenceConfig(configForm)
          }
          
          if (response.data.code === 200) {
            ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
            configDialogVisible.value = false
            loadConfigs()
          } else {
            ElMessage.error(response.data.message || '操作失败')
          }
        } catch (error) {
          console.error('操作失败：', error)
          ElMessage.error('操作失败')
        } finally {
          submitting.value = false
        }
      })
    }

    // 删除配置
    const deleteConfig = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除该配置吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteSequenceConfig(id)
        if (response.data.code === 200) {
          ElMessage.success('删除成功')
          loadConfigs()
        } else {
          ElMessage.error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败：', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 生成序列号
    const generateSeq = async () => {
      if (!generateForm.code) {
        ElMessage.warning('请先选择配置')
        return
      }
      
      generating.value = true
      try {
        const response = await generateSequence(generateForm.code)
        
        if (response.data.code === 200) {
          const sequence = response.data.data
          generatedList.value.unshift({
            code: generateForm.code,
            sequence: sequence,
            time: new Date().toLocaleString()
          })
          ElMessage.success('生成成功：' + sequence)
        } else {
          ElMessage.error(response.data.message || '生成失败')
        }
      } catch (error) {
        console.error('生成失败：', error)
        ElMessage.error('生成失败')
      } finally {
        generating.value = false
      }
    }

    // 清空历史
    const clearHistory = () => {
      generatedList.value = []
      ElMessage.success('已清空历史记录')
    }

    // 标签切换
    const handleTabClick = () => {
      if (activeTab.value === 'config') {
        loadConfigs()
      }
    }

    // 计算配置对话框标题
    const configDialogTitle = ref('')
    const updateDialogTitle = () => {
      configDialogTitle.value = isEdit.value ? '编辑配置' : '新增配置'
    }

    onMounted(() => {
      loadConfigs()
    })

    return {
      activeTab,
      loading,
      generating,
      submitting,
      configDialogVisible,
      isEdit,
      configFormRef,
      queryForm,
      pagination,
      configList,
      configForm,
      configRules,
      generateForm,
      generatedList,
      configDialogTitle,
      loadConfigs,
      resetQuery,
      showConfigDialog,
      resetConfigForm,
      submitConfig,
      deleteConfig,
      generateSequence: generateSeq,
      clearHistory,
      handleTabClick
    }
  }
}
</script>

<style scoped>
.sequence-management {
  padding: 20px;
  height: calc(100vh - 60px);
  overflow: auto;
  box-sizing: border-box;
  background: #f5f7fa;
}

:deep(.el-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-tabs__content) {
  flex: 1;
  overflow: hidden;
}

:deep(.el-tab-pane) {
  height: 100%;
  overflow: auto;
}

.search-form {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.config-section {
  padding: 0;
}

.config-section .el-table {
  margin-bottom: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  font-weight: 600;
  color: #606266;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0 10px;
  background: #fff;
}

.generate-section {
  padding: 0;
  overflow: auto;
}

.table-card {
  margin-bottom: 0;
  border: none;
}

:deep(.table-card .el-card__body) {
  padding: 0;
}
</style>
